package com.mfrs.demos;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.mfrs.ActionResult;
import com.mfrs.Constants;
import com.mfrs.FaceDetectionParam;
import com.mfrs.IFRSMobileService;

import hk.cic.demointegrationapp.R;

public class SettingsActivity extends Activity {

	private final String TAG = "FRSMobileDemo.Settings";
	
	private Button buttonSave;
	private Button buttonReset;
	
	private IFRSMobileService frsMobileService;
	private boolean isSvcConnected = false;
	
	public IFRSMobileService getFrsMobileService() {
		return frsMobileService;
	}

	private boolean connectToFrsMobileService() {
		Intent serviceIntent = new Intent();
		serviceIntent.setClassName("com.mfrs", "com.mfrs.FRSMobileService");
		isSvcConnected = bindService(serviceIntent, mServiceConnection,
				Context.BIND_AUTO_CREATE);
		Log.i(TAG,	"connectToFrsMobileService: "+ String.valueOf(isSvcConnected));
				
		return isSvcConnected;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "onDestroy");
		if (isSvcConnected){
			Log.i(TAG, "unbindservice");
			this.unbindService(mServiceConnection);
		}

	}
	private final ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(TAG, "onServiceConnected");
			
			frsMobileService = IFRSMobileService.Stub.asInterface(service);
			String[] owner = new String[1];
			String[] expiryDate = new String[1];
			
			
			try {				
				ActionResult ar = getFrsMobileService().getLicenseInfo(owner, expiryDate);
				if (ar.getCode() == ActionResult.CODE_Success){
					((TextView)findViewById(R.id.textLicenseOwner)).setText(owner[0]);
					Log.i(TAG, expiryDate[0]);
									
					if (expiryDate[0].equals(Constants.getDateNeverExpiryString()))
					{
						expiryDate[0] = "Never";
					}

					((TextView)findViewById(R.id.textExpiryDate)).setText(expiryDate[0]);
				}				
			} catch (RemoteException e) {
				Log.e(TAG, e.getMessage());
				e.printStackTrace();
			}
						
			buttonSave = (Button)findViewById(R.id.buttonSave);
			buttonReset = (Button)findViewById(R.id.buttonReset);
			
			buttonSave.setOnClickListener(new OnClickListener() {			
				@Override
				public void onClick(View v) {
					if (!saveConfig()){
						refreshConfig();
					}
					else {
						finish();
					}
	
				}
			});
			
			buttonReset.setOnClickListener(new OnClickListener() {			
				@Override
				public void onClick(View v) {
					refreshConfig();				
				}
			});
			
			refreshConfig();
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			Log.e(TAG, "Service Disconnected.");
		}

	};



	private void showAlertDialog(String message, String title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
		builder.setMessage(message).setTitle(title);
		AlertDialog dialog = builder.create();
		dialog.show();

	}

	private void showAlertDialog(ActionResult ar) {
		String message = "";
		if (ar.getCode() == ActionResult.CODE_FaceNotFound) {
			message = "CODE_FaceNotFound: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_FRSEngineError) {

			message = "CODE_FRSEngineError: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_ImageFormatNotSupport) {
			message = "CODE_ImageFormatNotSupport: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_InvalidFeatureData1) {
			message = "CODE_InvalidFeatureData1: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_InvalidFeatureData2) {
			message = "CODE_InvalidFeatureData2: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_LicenseExpired) {
			message = "CODE_LicenseExpired: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_LicenseNotValid) {
			message = "CODE_LicenseNotValid: " + ar.getRemark();
		} else if (ar.getCode() == ActionResult.CODE_UnknownError) {
			message = "CODE_UnknownError: " + ar.getRemark();
		}
		showAlertDialog(message, getResources().getString(R.string.title_err));
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_face_settings);
		// Show the Up button in the action bar.
		setupActionBar();
		
		
		Log.i(TAG, "onCreate");

		if (!isSvcConnected){
			isSvcConnected = connectToFrsMobileService();
			Log.i(TAG,	"onCreate Connect to FRS Mobile Service: " +	String.valueOf(isSvcConnected));			
		}
		Resources res = getResources();
		((TextView)findViewById(R.id.lblMinEyesDistance)).setText(
				String.format(res.getString(R.string.lbl_mineyedist), Constants.MIN_MIN_EYES_DISTANCE,  Constants.MAX_MIN_EYES_DISTANCE));
		((TextView)findViewById(R.id.lblMaxEyesDistance)).setText(
				String.format(res.getString(R.string.lbl_maxeyedist), Constants.MIN_MAX_EYES_DISTANCE,  Constants.MAX_MAX_EYES_DISTANCE));
		((TextView)findViewById(R.id.lbl_MaxNoFaces)).setText(
				String.format(res.getString(R.string.lbl_maxnooffaces), Constants.MIN_MAX_NUM_FACES,  Constants.MAX_MAX_NUM_FACES));
		((TextView)findViewById(R.id.lbl_MinFaceQualScore)).setText(
				String.format(res.getString(R.string.lbl_minfacescore), Constants.MIN_MIN_FACE_QUALITY_SCORE,  Constants.MAX_MIN_FACE_QUALITY_SCORE));
		
		
		
		
	}
	
	private boolean saveConfig(){		
		try {
			
			
			FaceDetectionParam faceDetectionParam = new FaceDetectionParam();
			
			faceDetectionParam.setMaxEyesDistance(
					Integer.parseInt(((EditText)findViewById(R.id.editTextMaxEyesDistance)).getText().toString()));
			
			faceDetectionParam.setMinEyesDistance(
					Integer.parseInt(((EditText)findViewById(R.id.editTextMinEyesDistance)).getText().toString()));
			
			faceDetectionParam.setMaxNumFaces(
					Integer.parseInt(((EditText)findViewById(R.id.editTextMaxNoFaces)).getText().toString()));
			
			faceDetectionParam.setMinFaceQualityScore(
					Float.parseFloat(((EditText)findViewById(R.id.editTextMinFaceScore)).getText().toString()));
			
			ActionResult ar = getFrsMobileService().setFaceDetectionParam(faceDetectionParam);

			Log.i(TAG, String.valueOf(ar.getCode()));
			if(ar.getCode() == ActionResult.CODE_Success){				
				Log.i(TAG, "Set Face Detection Param Successful");
				((TextView)findViewById(R.id.textViewError)).setText("");	
				return true;
			}else{
				showAlertDialog(ar);
			}
			((TextView)findViewById(R.id.textViewError)).setText(ar.getRemark());
			
		} catch (RemoteException e) {
			e.printStackTrace();			
		}
		return false;
	}
	
	private void refreshConfig(){
		Log.i(TAG, "refreshConfig");
		try {		
			FaceDetectionParam faceDetectionParam = new FaceDetectionParam();
			ActionResult ar = getFrsMobileService().getFaceDetectionParam(faceDetectionParam);
			if(ar.getCode() == ActionResult.CODE_Success){
				((EditText)findViewById(R.id.editTextMaxEyesDistance)).setText(String.valueOf(faceDetectionParam.getMaxEyesDistance()));
				((EditText)findViewById(R.id.editTextMinEyesDistance)).setText(String.valueOf(faceDetectionParam.getMinEyesDistance()));
				((EditText)findViewById(R.id.editTextMaxNoFaces)).setText(String.valueOf(faceDetectionParam.getMaxNumFaces()));
				((EditText)findViewById(R.id.editTextMinFaceScore)).setText(String.valueOf(faceDetectionParam.getMinFaceQualityScore()));
				
				Log.i(TAG, "getMaxEyesDistance: " + String.valueOf(faceDetectionParam.getMaxEyesDistance()));				
				Log.i(TAG, "getMinEyesDistance: " + String.valueOf(faceDetectionParam.getMinEyesDistance()));
				Log.i(TAG, "getMinFaceQualityScore: " + String.valueOf(faceDetectionParam.getMinFaceQualityScore()));
				Log.i(TAG, "getMaxNumFaces: " + String.valueOf(faceDetectionParam.getMaxNumFaces()));
			}else{
				showAlertDialog(ar);
			}			
		} catch (RemoteException e) {
			e.printStackTrace();
		}	
	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.settings, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
